package com.zt.location.modules.business.scheduler;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.zt.location.common.utils.SysCache;
import com.zt.location.modules.base.entity.RealTimeEntity;
import com.zt.location.modules.base.service.RealTimeService;
import com.zt.location.modules.business.message.TaskData;

@Component
public class Scheduler {

	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Autowired
	private RealTimeService realTimeService;

	// 每隔5分钟执行一次
	@Scheduled(fixedRate = 1000 * 60)
	public void checkMachineStatus() {
		System.out.println("定时任务执行时间：" + dateFormat.format(new Date()));
		for (TaskData temp : SysCache.getMachineAll()) {
			if (temp.getStatus() == 2 && !compareMachine(temp)) {
				realTimeService.updateMainchStatus(temp.getReaderID());
				temp.setStatus(1);
				SysCache.addMachineObject(temp.getReaderIP(), temp);
			} 
		}
		
		checkSpeed();
	}

	private void checkSpeed() {
		List<RealTimeEntity> realTimeEntityList = realTimeService.queryInitList();
		if (null != realTimeEntityList && realTimeEntityList.size() > 0) {
			for (RealTimeEntity realTimeEntity : realTimeEntityList) {
				if (realTimeEntity.getSpeen() > 0 && null != realTimeEntity.getUpdateTime()) {
					long time=0;
					try {
						SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
					    time = simpleDateFormat.parse(realTimeEntity.getUpdateTime().replace(".0","")).getTime();  
					} catch (Exception e) { 
					}
					
					if (System.currentTimeMillis() - time >= 30 * 1000) {
						realTimeService.updateMainchSpeed(realTimeEntity.getReaderId());
					}
				}
			}
		}
	}

	private boolean compareMachine(TaskData taskData) {
		for (TaskData temp : SysCache.getMachineAll()) {
			if (!temp.getReaderIP().equals(taskData.getReaderIP())
					&& temp.getCurrentState().equals(taskData.getCurrentState())) {
				if (taskData.getTitleStartNo() <= temp.getTitleNo() && taskData.getTitleEndNo() >= temp.getTitleNo()) {
					return true;
				}
			}
		}
		return false;
	}

}